package com.layblog.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.layblog.common.lang.Result;
import com.layblog.entity.Comment;
import com.layblog.entity.Post;
import com.layblog.entity.User;
import com.layblog.entity.UserMessage;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author JackLin
 * @since 2021-07-30
 */

@Controller
public class CommentController extends BaseController {


    /**
     * 顶/踩评论
     *
     * @author: jacklin
     * @since 2022/8/11 23:59
     **/
    @ResponseBody
    @PostMapping(value = "/comment/zanSet")
    public Result zanSet(Long id, String field) {

        Comment comment = commentService.getById(id);
        Assert.notNull(comment, "该评论已被删除！");

        if (field.equals("voteUp")) {
            Integer voteUpCount = ObjectUtil.isNull(comment.getVoteUp()) ? 0 : comment.getVoteUp();
            comment.setVoteUp(voteUpCount + 1);
        } else if (field.equals("voteDown")) {
            Integer voteDownCount = ObjectUtil.isNull(comment.getVoteDown()) ? 0 : comment.getVoteDown();
            comment.setVoteDown(voteDownCount + 1);
        }
        commentService.updateById(comment);
        return Result.succ();
    }

    /**
     * 发布评论，可以是评论文章，也可以是回复评论，需要传文章id，和评回复的评论ID(parentId)
     * <p>
     * 发布评论还涉及到如下几个方面：
     * 1.简单的逻辑判断
     * 2.文章评论数加一
     * 3.侧边栏的本周热议要重新排行
     * 4.通知文章作者有新的评论
     * 5.通知@的用户有人回复了你的评论
     * </p>
     *
     * @param pid      评论的文章id
     * @param parentId 回复的评论id
     * @param content  评论内容
     * @return
     */
    @ResponseBody
    @PostMapping("/post/reply")
    public Result commentReply(Long pid, Long parentId, String content) {
        Assert.notNull(pid, "找不到对应文章！");
        Assert.hasLength(content, "评论内容不能为空！");

        Post post = postService.getById(pid);
        Assert.isTrue(post != null, "该文章已被删除");

        Comment comment = new Comment();
        comment.setPostId(pid);
        comment.setContent(content);
        comment.setUserId(getProfileId());
        comment.setCreated(new Date());
        comment.setModified(new Date());
        comment.setLevel(0);
        comment.setVoteDown(0);
        comment.setVoteUp(0);
        commentService.save(comment);

        // 评论数量加一
        post.setCommentCount(post.getCommentCount() + 1);
        postService.saveOrUpdate(post);

        //更新首页排版版的评论数量
        postService.incrZsetValueAndUnionForLastWeekRank(comment.getPostId(), true);

        //自己的评论不需要通知
        if (post.getUserId() != getProfileId()) {
            // 通知作者
            UserMessage message = new UserMessage();
            message.setPostId(pid);
            message.setCommentId(comment.getId());
            message.setFromUserId(getProfileId());
            message.setToUserId(post.getUserId());
            message.setType(1);
            message.setContent(comment.getContent());
            message.setCreated(new Date());
            message.setModified(new Date());
            userMessageService.save(message);
            wsService.sendMessCountToUser(message.getToUserId(), null);
        }


        /**
         * 通知@的人
         *
         * 当我们点击评论的时候，评论框会出现@当前评论的用户名称，如下：@JackLin 这是一条没被采纳的回帖。
         * 我们发送的需要告知这个用户，根据@的特点，我么提取@与空格之间的用户名，然后搜索出来再报告消息
         */
        if (content.startsWith("@")) {
            String username = content.substring(1, content.indexOf(" "));
            System.out.println(username);
            QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", username);
            User user = userService.getOne(wrapper);
            if (user != null) {
                UserMessage message2 = new UserMessage();
                message2.setPostId(pid);
                message2.setCommentId(comment.getId());
                message2.setFromUserId(getProfileId());
                message2.setToUserId(user.getId());
                message2.setType(3);
                message2.setContent(comment.getContent());
                message2.setCreated(new Date());
                message2.setModified(new Date());
                userMessageService.save(message2);
                wsService.sendMessCountToUser(message2.getToUserId(), null);
            }
        }

        return Result.succ("评论成功", null, "/post/" + pid);
    }

    /**
     * 删除评论
     *
     * @param id
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/post/jieda-delete/")
    public Result delComment(Long id) {

        Assert.notNull(id, "评论id不能为空！");

        Comment comment = commentService.getById(id);

        Assert.notNull(comment, "找不到对应评论！");

        if (comment.getUserId() != getProfileId()) {
            return Result.fail("不是你发表的评论！");
        }
        commentService.removeById(id);

        // 评论数量减一
        Post post = postService.getById(comment.getPostId());
        post.setCommentCount(post.getCommentCount() - 1);
        postService.saveOrUpdate(post);

        //评论数量减一
        postService.incrZsetValueAndUnionForLastWeekRank(comment.getPostId(), false);

        return Result.succ(null);
    }

}
